package com.bungarus.utils;

import java.net.*;
import java.util.Enumeration;

public class IPAddressUtils {

    public static void main(String[] args) {
        try {
            IPAddressUtils.getLocalHostLANAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }
    /**
     * 多网卡场景获取真实IP
     *
     * @return InetAddress
     */
    public static InetAddress getLocalHostLANAddress() throws UnknownHostException {
        try {
            for(Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();e.hasMoreElements();) {
                NetworkInterface currentNetwork = e.nextElement();
                for(InterfaceAddress address : currentNetwork.getInterfaceAddresses()) {
                    if(currentNetwork.isLoopback() || !currentNetwork.isUp() || currentNetwork.isVirtual()) {
                        continue;
                    }
                    if(address.getAddress() instanceof Inet4Address) {
                        Inet4Address inet4Address = (Inet4Address)address.getAddress();
                        System.out.println("======== IP: " + inet4Address.getHostAddress() + " ==========");
                        System.out.println("inet4Address.isAnyLocalAddress(): " + inet4Address.isAnyLocalAddress());
                        System.out.println("inet4Address.isLinkLocalAddress(): " + inet4Address.isLinkLocalAddress());
                        System.out.println("inet4Address.isMCGlobal(): " + inet4Address.isMCGlobal());
                        System.out.println("inet4Address.isMCLinkLocal(): " + inet4Address.isMCLinkLocal());
                        System.out.println("inet4Address.isMCNodeLocal(): " + inet4Address.isMCNodeLocal());
                        System.out.println("inet4Address.isMCOrgLocal(): " + inet4Address.isMCOrgLocal());
                        System.out.println("inet4Address.isMCSiteLocal(): " + inet4Address.isMCSiteLocal());
                        System.out.println("inet4Address.isMulticastAddress(): " + inet4Address.isMulticastAddress());
                        System.out.println("inet4Address.isSiteLocalAddress(): " + inet4Address.isSiteLocalAddress());
                        if(inet4Address.isSiteLocalAddress()) {
                            return inet4Address;
                        }
                    }
                }
            }
            return InetAddress.getLocalHost();
        } catch (SocketException | UnknownHostException e) {
            throw  new RuntimeException(e);
        }
    }
}